package org.totoro.lock;

import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author YHL
 * @version V1.0
 * @Description:
 * @date 2018-12-05
 */
public class DistributedLockSupport {

    private LockBean lockBean;

    private String ephemeralSequential;

    private ReentrantLock reentrantLock;

    /**
     * 默认非公平锁
     */
    public DistributedLockSupport() {
        reentrantLock = new ReentrantLock();
    }

    /**
     * ture：公平锁
     * <p>
     * false：非公平锁
     *
     * @param fair
     */
    public DistributedLockSupport(boolean fair) {
        reentrantLock = new ReentrantLock(fair);
    }

    public byte[] getLockBean() {
        String lockBeanToJson = JSONObject.toJSONString(this.lockBean);
        return lockBeanToJson.getBytes();
    }

    public DistributedLockSupport setEphemeralSequential(String ephemeralSequential) {
        this.ephemeralSequential = ephemeralSequential;
        return this;
    }

    public void unlock() {

        if (reentrantLock.isLocked()) {
            reentrantLock.unlock();
        }

    }

    public void lock() {
        reentrantLock.unlock();
    }

}
